module RPMCounter(clk, pulse, dig1, dig2, dig3);

	input clk;    //assuming 10kHz clk
	input pulse;  //input from hall-effect sensor
	
	//3 decimal digit display, dig# is BCD
	output reg [3:0]	dig1;
	output reg [3:0]	dig2;
	output reg [3:0]	dig3;
	
	wire [3:0]	dig1w;
	wire [3:0]	dig2w;
	wire [3:0]	dig3w;
	
	reg [3:0]	ndig1;
	reg [3:0]	ndig2;
	reg [3:0]	ndig3;
	
	reg			PULSE_VALUE;
	reg			nPULSE_VALUE;
	
	reg [15:0]	COUNTER1;
	reg [15:0]	nCOUNTER1;
	reg [15:0]	COUNTER2;
	reg [15:0]	nCOUNTER2;
	
	reg [15:0]	PULSECOUNT;
	
	reg [15:0]	TIMER;
	reg [15:0]	nTIMER;
	
	reg			UPDATE_DISPLAY;

	RPM_LUT LUT((PULSECOUNT<<1), dig1w, dig2w, dig3w);
  
	always@(COUNTER1 or COUNTER2 or PULSE_VALUE or pulse or TIMER or dig1w or dig2w or dig3w) begin
		if(PULSE_VALUE == 1'b1 && pulse == 1'b0) begin	//on negative edge
			nCOUNTER1 = TIMER;                         	//reset counter
			nCOUNTER2 = TIMER;
			ndig1 = dig1w;											//update display value
			ndig2 = dig2w;
			ndig3 = dig3w;
		end
		else begin
			nCOUNTER2 = COUNTER2 + 1;							//otherwise, increment counter
		end

		if(COUNTER2 <= COUNTER1) begin						//overflow occured
			PULSECOUNT = (16'b1111111111111111 - COUNTER1) + COUNTER2;
		end
		else begin													//no overflow occured
			PULSECOUNT = COUNTER2 - COUNTER1;
		end
		
		if(TIMER == 16'd10000) begin							//reset timer every second
			nTIMER = 0;
			UPDATE_DISPLAY = 1;
		end
		else begin
			nTIMER = TIMER + 1;
			UPDATE_DISPLAY = 0;
		end
		
		nPULSE_VALUE = pulse;									//always update pulse value
	end
  
	always@(posedge clk) begin
		if(UPDATE_DISPLAY) begin
			dig1 <= ndig1;
			dig2 <= ndig2;
			dig3 <= ndig3;
		end
		COUNTER1 <= nCOUNTER1;
		COUNTER2 <= nCOUNTER2;
		PULSE_VALUE <= nPULSE_VALUE;
		TIMER <= nTIMER;
	end
  
	initial begin
		dig1 = 4'hF;
		dig2 = 4'hF;
		dig3 = 4'hF;
		ndig1 = 4'hF;
		ndig2 = 4'hF;
		ndig3 = 4'hF;	 
		PULSE_VALUE = 1'b0;
		nPULSE_VALUE = 1'b0;
		COUNTER1 = 16'd0;
		nCOUNTER1 = 16'd0;
		COUNTER2 = 16'd0;
		nCOUNTER2 = 16'd0;
		TIMER = 16'd0;
		nTIMER = 16'd0;
		UPDATE_DISPLAY = 0;
	end
endmodule